package service

import (
	"errors"
	"strconv"
	"tiktok2023/middleware"
	"tiktok2023/model"
	"tiktok2023/utils"

	"github.com/gin-gonic/gin"
)

const (
	AvatarDefault = "https://ui-avatars.com/api/?background=8e44ad&rounded=true&name=%E6%BB%95&color=fff" // 头像
	//简介
	SignatureDefault = "这个人神秘，什么都没留下"

	BackgroundImageDefault = "https://gitee.com/static/images/logo-black.svg?t=158106664" //背景图片
	//关注数
	FollowCountDefault = 99
	//粉丝数
	FollowerCountDefault = 100
	//是否已关注
	IsFollowDefault = false
	//总喜欢数
	TotalFavoriteDefault = 1000
	//作品数
	WorkCountDefault = 20
	//收藏数
	FavoriteCountDefault = 54
)

type UserService struct {
}

type Response struct {
	StatusCode int32  `json:"status_code"`
	StatusMsg  string `json:"status_msg,omitempty"`
}

type RegisterAndLoginResopnse struct {
	Response
	UserId uint64 `json:"user_id"`
	Token  string `json:"token"`
}

type GetUserResponse struct {
	Response
	model.User `json:"user"`
}

func (u UserService) HandleRegister(c *gin.Context) (resp *RegisterAndLoginResopnse, err error) {
	username := c.Query("username")
	password := c.Query("password")
	if len(username) > 32 || len(password) > 32 {
		return nil, errors.New("用户名或密码过长")
	}
	//需要让数据库里面不能存储明文密码
	user := model.TableUser{
		Name:            username,
		Avatar:          AvatarDefault,
		Signature:       SignatureDefault,
		BackgroundImage: BackgroundImageDefault,
		FollowCount:     FollowCountDefault,
		FollowerCount:   FollowerCountDefault,
		IsFollow:        false,
		TotalFavorited:  strconv.Itoa(TotalFavoriteDefault),
		WorkCount:       WorkCountDefault,
		FavoriteCount:   FavoriteCountDefault,
	}
	// 当数据中有这个人的时候，会返回错误
	if err := model.Db.Where("name = ?", username).First(&user).Error; err == nil {
		return &RegisterAndLoginResopnse{
			Response: Response{
				StatusCode: 1,
				StatusMsg:  model.ExitsError,
			},
			UserId: 0,
			Token:  "",
		}, err
	}
	// 到这里时用户不存在，即一个新用户
	password, err1 := utils.Encoder(password)
	if err1 != nil {
		return &RegisterAndLoginResopnse{
			Response: Response{
				StatusCode: 1,
				StatusMsg:  model.ExitsError,
			},
			UserId: 0,
			Token:  "",
		}, err1
	}
	// 把加密后的密码存储到密码中
	user.Password = password
	if err := model.Db.Create(&user).Error; err != nil {
		return nil, err
	}
	token, err2 := middleware.GenerateToken(user.Id)
	if err2 != nil {
		return &RegisterAndLoginResopnse{
			Response: Response{
				StatusCode: 1,
			},
			UserId: 0,
			Token:  "",
		}, err2
	}
	return &RegisterAndLoginResopnse{
		Response: Response{
			StatusCode: 0,
			//StatusMsg:  "",
		},
		UserId: user.Id,
		Token:  token,
	}, nil
}

func (u UserService) HandleLogin(c *gin.Context) (resp *RegisterAndLoginResopnse, err error) {
	username := c.Query("username")
	password := c.Query("password")
	user := model.TableUser{}
	// 当数据库中有这个人的时候，会返回错误
	if err := model.Db.Where("name = ?", username).First(&user).Error; err != nil {
		return &RegisterAndLoginResopnse{
			Response: Response{
				StatusCode: 1,
				StatusMsg:  model.NotExitsEoor,
			},
			UserId: 0,
			Token:  "",
		}, err
	}
	// 到这里时用户存在，判断密码是否匹配
	login, loginErr := utils.Decoder(password, user.Password)
	if loginErr != nil {
		return &RegisterAndLoginResopnse{
			Response: Response{
				StatusCode: 1,
			},
		}, loginErr
	}
	if !login {
		return &RegisterAndLoginResopnse{
			Response: Response{
				StatusCode: 1,
				StatusMsg:  "密码错误",
			},
		}, err
	}
	//获取token
	token, tokenErr := middleware.GenerateToken(user.Id)
	if tokenErr != nil {
		return &RegisterAndLoginResopnse{
			Response: Response{
				StatusCode: 1,
			},
		}, tokenErr
	}
	return &RegisterAndLoginResopnse{
		Response: Response{
			StatusCode: 0,
			StatusMsg:  "登录成功",
		},
		UserId: user.Id,
		Token:  token,
	}, nil
}

func (u UserService) HandleGetUser(c *gin.Context) (resp *GetUserResponse, err error) {
	token := c.Query("token")
	userIdStr := c.Query("user_id")
	userId, _ := strconv.ParseUint(userIdStr, 10, 64)
	// 判断token
	if len(token) == 0 {
		return nil, errors.New("token无效")
	}
	if userId == 0 {
		Claim, _ := middleware.ParseToken(token)
		userId = Claim.UserId
	}
	user := model.TableUser{}
	if err := model.Db.Where("id = ?", userId).First(&user).Error; err != nil {
		return nil, err
	}
	// 到这里找到了
	return &GetUserResponse{
		Response: Response{
			StatusCode: 0,
		},

		User: model.User{
			Id:              int64(user.Id),
			Name:            user.Name,
			FollowCount:     FollowCountDefault,
			FollowerCount:   FollowerCountDefault,
			IsFollow:        false,
			Avatar:          AvatarDefault,
			BackgroundImage: BackgroundImageDefault,
			Signature:       SignatureDefault,
			TotalFavorited:  strconv.Itoa(TotalFavoriteDefault),
			WorkCount:       WorkCountDefault,
			FavoriteCount:   FavoriteCountDefault,
		},
	}, nil
}
